#include "../GameLogic/IGrid.h"
#include "../GameLogic/ICell.h"

#include "Grid.h"


using namespace cocos2d;
CGrid::CGrid(CCSize size)
	: IGrid(size) , m_gameLayer(NULL)
{

}

CCTMXLayer * CGrid::GetCCTMXLayer(){
	return m_gameLayer;
}

void CGrid::SetCCTMXLayer(CCTMXLayer *layer){
	m_gameLayer = layer;
}

bool CGrid::LoadLevel()
{
	if (m_gameLayer)
	{
		ParseProperty(m_gameLayer);
		ParseGrid(m_gameLayer);
		return true;
	}
	return false;
}

void CGrid::ParseProperty(CCTMXLayer *layer)
{
	if (layer)
	{
		CCTMXTilesetInfo* tileInfo = layer->getTileSet();
		unsigned int tileLowerBound = tileInfo->m_uFirstGid;
		int size = int(tileInfo->m_tImageSize.width *  tileInfo->m_tImageSize.height / tileInfo->m_tTileSize.width / tileInfo->m_tTileSize.height);
		CellFactory::sharedCellFactory()->SetCellTypeRange(tileLowerBound, tileLowerBound + size - 1);
	}
}

void CGrid::ParseGrid(CCTMXLayer *layer)
{
	if (layer)
	{
		
		for (int i = 0; i < GetSize().width; i++)
		{
			for (int j = 0; j < GetSize().height; j++)
			{
				CCPoint pos = CCPointMake(i,j);
				int tileId = layer->tileGIDAt(pos);
				if (tileId > 0)
				{
					ReplaceCell(pos, tileId);
				}
			}
		}
	}
}

void CGrid::RefreshDisplayLayer()
{
	for (int i = 0; i < GetSize().width; i++)
		for (int j = 0; j < GetSize().height; j++)
		{
			CCPoint p = CCPointMake(i, j);
			ICell* cell = GetCell(p);
			if (cell)
			{
				if (m_gameLayer->tileGIDAt(p) != cell->GetType())
				{
					m_gameLayer->setTileGID(cell->GetType(), p);
				}
			}
			else if (m_gameLayer->tileGIDAt(p) != 0)
			{
				m_gameLayer->removeTileAt(p);			
			}
		}
}